package com.usian.quartz;

import com.usian.mapper.LocalMessageMapper;
import com.usian.mapper.TbItemMapper;
import com.usian.mapper.TbOrderItemMapper;
import com.usian.mapper.TbOrderMapper;
import com.usian.mq.MQSender;
import com.usian.pojo.*;
import com.usian.redis.RedisClient;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

public class OrderQuartz implements Job {

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    @Autowired
    private TbItemMapper tbItemMapper;

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private LocalMessageMapper localMessageMapper;

    @Autowired
    private MQSender mqSender;

    @Autowired
    private RedisClient redisClient;

    /**
     * 关闭超时订单
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//        查询超时订单
        if (redisClient.setnx("SETNX_LOCK_ORDER_KEY", "1", 30L)) {
            List<TbOrder> tbOrders = tbOrderMapper.selectOvertimeOrder();

//        关闭超时订单
        for (TbOrder tbOrder : tbOrders) {
            tbOrder.setStatus(6);
            tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
//        超时订单的商品库存数量加回去   恢复库存
            TbOrderItemExample tbOrderItemExample = new TbOrderItemExample();
            TbOrderItemExample.Criteria criteria = tbOrderItemExample.createCriteria();
            criteria.andOrderIdEqualTo(tbOrder.getOrderId());
            List<TbOrderItem> tbOrderItems = tbOrderItemMapper.selectByExample(tbOrderItemExample);
            for (TbOrderItem tbOrderItem : tbOrderItems) {
                TbItem tbItem = tbItemMapper.selectByPrimaryKey(Long.valueOf(tbOrderItem.getItemId()));
                tbItem.setNum(tbItem.getNum()+tbOrderItem.getNum());
                tbItem.setUpdated(new Date());
                tbItemMapper.updateByPrimaryKeySelective(tbItem);
                }
//            本地消息记录表发送失败的重新发送
//            查询发送失败的集合  state=0  list
            LocalMessageExample localMessageExample = new LocalMessageExample();
            LocalMessageExample.Criteria criteria1 = localMessageExample.createCriteria();
            criteria1.andStateEqualTo(0);
            List<LocalMessage> localMessageList = localMessageMapper.selectByExample(localMessageExample);
            for (LocalMessage localMessage : localMessageList) {
                mqSender.sendMsg(localMessage);
            }
        }
            redisClient.del("SETNX_LOCK_ORDER_KEY");
        }else {
            System.out.println("其他任务正在执行，请稍后");
        }
    }


}
